<?php

namespace app\admin\controller;

use wechat\src\WeChat;

/**
 * 微信菜单设置，
 */
class Wechatbutton extends base
{

    protected $wechat;

    public function _initialize()
    {
        $this->wechat = (new WeChat);
        $this->wechat->valid();

    }

    /**
     * 读取菜单
     */
    public function index()
    {
        $data = model('system')
            ->where(['type' => 'button'])
            ->column('value');
        $this->assign('data', $data['0']);
        return $this->fetch();
    }

    /**
     * 自定义菜单首页
     * Eddy 沈阳 0711
     */
    public function menu()
    {
        ## 查询当前公众号的自定义菜单
        $mid = Session('mid');
        $list = db('mp_menu')
            ->where([ 'pindex' => 0])
            ->select();

        $data = [];
        ## 如果表中存在，则直接读取；否则通过接口获取自定义菜单，并写入数据库
        if (!empty($list)) {
            foreach ($list as $key => $item) {
                $list[$key]['sub'] = db('mp_menu')
                    ->where(['pindex' => $item['index']])
                    ->select();
            }
            $data['list'] = $list;
        } else {

            $data['list'] = array();
        }
        $this->assign('list',$list);
        return $this->fetch();
    }

    public function delMpMenu()
    {
        deleteMpMenu();
        db('mp_menu')
            ->where('1=1')
            ->delete();

    }

    /**
     * 自定义菜单保存编辑
     * Eddy 0711
     */
    public function menuedit()
    {
        if ($this->request->isAjax()) {

            $post = input('post.');
            $data = $post['data'];
            if (empty($data)) {
                deleteMpMenu();//空菜单认为删除全部菜单
                ajaxMsg(1, '保存成功');
            }
            db('mp_menu')->where('1=1')->delete();

            foreach ($data as $key => $vo) {
                if (isset($vo['content'])) {
                    $data[$key]['content'] = str_replace('"', "'", $vo['content']);
                }
            }
            $_S = false;
            foreach ($data as $key => $val) {
                $_S = db('mp_menu')->insert($data[$key]);
            }
            if ($_S) {
                $result = db('mp_menu')
                    ->field('id,index,pindex,name,type,content')
                    ->where('status', '1')
                    ->order('sort ASC,id ASC')
                    ->select();
                $menu_type = [
                    'view' => '跳转URL',
                    'click' => '点击推事件',
                    'scancode_push' => '扫码推事件',
                    'scancode_waitmsg' => '扫码推事件且弹出“消息接收中”提示框',
                    'pic_sysphoto' => '弹出系统拍照发图',
                    'pic_photo_or_album' => '弹出拍照或者相册发图',
                    'pic_weixin' => '弹出微信相册发图器',
                    'location_select' => '弹出地理位置选择器',
                ];
                foreach ($result as &$row) {
                    empty($row['content']) && $row['content'] = uniqid();
                    switch ($row['type']) {
                        case 'miniprogram':
                            list($row['appid'], $row['url'], $row['pagepath']) = explode(',', $row['content'] . ',,');
                            break;
                        case 'view':
                            $row['url'] = preg_match('#^(\w+:)?//#i', $row['content']) ? $row['content'] : url($row['content'], '', true, true);
                            break;
                        case 'event':
                            if (isset($menu_type[$row['content']])) {
                                $row['type'] = $row['content'];
                                $row['key'] = "wechat_menu#id#{$row['id']}";
                            }
                            break;
                        case 'media_id':
                            $row['media_id'] = $row['content'];
                            break;
                        default :
                            (!in_array($row['type'], $menu_type)) && $row['type'] = 'click';
                            $row['key'] = "{$row['content']}";
                    }
                    unset($row['content']);
                }
                $menus = $this->GetRreeByMpMenu($result, 'index', 'pindex', 'sub_button');
                foreach ($menus as &$menu) {
                    unset($menu['index'], $menu['pindex'], $menu['id']);
                    if (empty($menu['sub_button'])) {
                        continue;
                    }
                    foreach ($menu['sub_button'] as &$submenu) {
                        unset($submenu['index'], $submenu['pindex'], $submenu['id']);
                    }
                    unset($menu['type']);
                }

                $result = $this->wechat->instance('button')->create(['button' => $menus]);
                if (isset($result['errcode'])) {
                    ajaxMsg(0, 'errCode: ' . $result['errcode'] . ' errMsg: ' . $result['errmsg']);
                } elseif ($result == true) {
                    ajaxMsg(1, '发布成功');
                }
            }

        }
    }


    function GetRreeByMpMenu($list, $id = 'id', $pid = 'pid', $son = 'sub')
    {
        $tree = $map = [];
        foreach ($list as $item) {
            $map[$item[$id]] = $item;
        }
        foreach ($list as $item) {
            if (isset($item[$pid]) && isset($map[$item[$pid]])) {
                $map[$item[$pid]][$son][] = &$map[$item[$id]];
            } else {
                $tree[] = &$map[$item[$id]];
            }
        }
        unset($map);
        return $tree;
    }

    /**
     * 保存菜单并发布菜单
     */
    public function save()
    {
        $d = $this->wechat->instance('button')->create($this->request->post('data', '', null));
        if ($d == '1') {
            model('system')
                ->save(['value' => $this->request->post('data', '', null)], ['type' => 'button']);
            return ajax_info('修改成功！', 'index');
        } else {
            return ajax_info($d['errmsg'] . ',没有修改');

        }
    }
}
